/**
 * 游戏管理器 - 负责初始化、加载和管理游戏
 */

// 导入游戏工具模块
import * as gameUtils from '../../game-utils.js';

/**
 * 游戏管理器类
 * 负责游戏的初始化、加载和状态管理
 */
class GameManager {
    constructor() {
        this.isInitialized = false;
        this.gameData = null;
        this.gameContainer = null;
        this.resourcePanel = null;
    }
    
    /**
     * 初始化游戏
     * @param {string} containerId - 游戏容器的DOM ID
     */
    async init(containerId) {
        if (this.isInitialized) return;
        
        // 获取游戏容器
        this.gameContainer = document.getElementById(containerId);
        if (!this.gameContainer) {
            console.error('游戏容器未找到:', containerId);
            return;
        }
        
        try {
            // 显示加载中状态
            this.showLoading();
            
            // 加载游戏数据
            this.gameData = gameUtils.getGameData();
            if (!this.gameData) {
                this.gameData = gameUtils.getInitialGameData();
                gameUtils.setGameData(this.gameData);
            }
            
            // 初始化游戏界面
            await this.initGameInterface();
            
            // 初始化事件监听器
            this.setupEventListeners();
            
            // 启动资源更新定时器
            this.startResourceTimer();
            
            this.isInitialized = true;
            console.log('游戏初始化完成');
            
            // 显示欢迎消息
            this.showNotification('欢迎来到镇长日志游戏！', 'success');
        } catch (error) {
            console.error('游戏初始化失败:', error);
            this.showError('游戏初始化失败，请刷新页面重试');
        }
    }
    
    /**
     * 显示加载中状态
     */
    showLoading() {
        if (!this.gameContainer) return;
        
        this.gameContainer.innerHTML = `
            <div class="flex flex-col items-center justify-center p-8">
                <div class="loading-spinner mb-4"></div>
                <p class="text-lg font-medium">正在加载游戏数据...</p>
            </div>
        `;
    }
    
    /**
     * 显示错误信息
     * @param {string} message - 错误信息
     */
    showError(message) {
        if (!this.gameContainer) return;
        
        this.gameContainer.innerHTML = `
            <div class="flex flex-col items-center justify-center p-8 text-danger">
                <i class="fa fa-exclamation-circle text-5xl mb-4"></i>
                <p class="text-lg font-medium">${message}</p>
                <button class="mt-4 px-4 py-2 bg-primary text-white rounded hover:bg-primary/90" 
                        onclick="location.reload()">
                    <i class="fa fa-refresh mr-2"></i>刷新页面
                </button>
            </div>
        `;
    }
    
    /**
     * 显示通知
     * @param {string} message - 通知内容
     * @param {string} type - 通知类型：info, success, warning, error
     */
    showNotification(message, type = 'info') {
        if (window.showNotification) {
            window.showNotification(message, '', type);
        } else {
            console.log(`[${type}] ${message}`);
        }
    }
    
    /**
     * 初始化游戏界面
     */
    async initGameInterface() {
        if (!this.gameContainer) return;
        
        // 构建游戏界面的基本框架
        this.gameContainer.innerHTML = `
            <div class="game-container">
                <!-- 主游戏区域 -->
                <div class="main-game-area">
                    <!-- 资源面板 -->
                    <div id="resource-panel" class="resource-panel mb-4">
                        <h2 class="text-lg font-bold mb-3 flex items-center">
                            <i class="fa fa-cube text-primary mr-2"></i>资源
                        </h2>
                        <div id="resources-grid" class="resource-grid">
                            <!-- 资源卡片将通过JavaScript动态生成 -->
                        </div>
                    </div>
                    
                    <!-- 游戏标签页 -->
                    <div class="game-tab-container mb-4">
                        <div class="game-tabs" id="game-tabs">
                            <div class="game-tab active" data-tab="buildings">
                                <i class="fa fa-building mr-1"></i>建筑
                            </div>
                            <div class="game-tab" data-tab="events">
                                <i class="fa fa-bell mr-1"></i>事件
                            </div>
                            <div class="game-tab" data-tab="quests">
                                <i class="fa fa-tasks mr-1"></i>任务
                            </div>
                        </div>
                        
                        <div class="game-tab-content">
                            <div id="tab-buildings" class="tab-content active">
                                <div id="buildings-list" class="space-y-3">
                                    <!-- 建筑卡片将通过JavaScript动态生成 -->
                                    <p class="text-gray-500 text-center py-8">加载中...</p>
                                </div>
                            </div>
                            
                            <div id="tab-events" class="tab-content hidden">
                                <div id="events-list" class="space-y-3">
                                    <!-- 事件卡片将通过JavaScript动态生成 -->
                                    <p class="text-gray-500 text-center py-8">暂无事件</p>
                                </div>
                            </div>
                            
                            <div id="tab-quests" class="tab-content hidden">
                                <div id="quests-list" class="space-y-3">
                                    <!-- 任务卡片将通过JavaScript动态生成 -->
                                    <p class="text-gray-500 text-center py-8">暂无任务</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 侧边信息区域 -->
                <div class="side-info-area">
                    <!-- 游戏状态信息 -->
                    <div class="bg-white rounded-lg shadow-sm p-4 mb-4">
                        <h2 class="text-lg font-bold mb-3 flex items-center">
                            <i class="fa fa-info-circle text-accent mr-2"></i>状态信息
                        </h2>
                        <div class="space-y-2">
                            <div class="flex justify-between">
                                <span class="text-gray-600">当前阶段:</span>
                                <span id="game-stage" class="font-medium">生存阶段</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">人口:</span>
                                <span id="game-population" class="font-medium">5/10</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">日期:</span>
                                <span id="game-day" class="font-medium">第1天</span>
                            </div>
                        </div>
                        
                        <div class="mt-4">
                            <button id="recruit-villager" class="w-full px-3 py-2 bg-primary text-white rounded hover:bg-primary/90 transition-colors">
                                <i class="fa fa-user-plus mr-2"></i>招募村民
                            </button>
                        </div>
                    </div>
                    
                    <!-- 游戏日志 -->
                    <div class="bg-white rounded-lg shadow-sm p-4">
                        <h2 class="text-lg font-bold mb-3 flex items-center">
                            <i class="fa fa-history text-primary mr-2"></i>日志
                        </h2>
                        <div id="game-log" class="game-log">
                            <!-- 日志条目将通过JavaScript动态生成 -->
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 初始化游戏标签页切换功能
        this.initTabSwitching();
    }
    
    /**
     * 初始化标签页切换功能
     */
    initTabSwitching() {
        const tabs = document.querySelectorAll('.game-tab');
        const tabContents = document.querySelectorAll('.tab-content');
        
        tabs.forEach(tab => {
            tab.addEventListener('click', () => {
                const tabId = tab.getAttribute('data-tab');
                
                // 更新标签页状态
                tabs.forEach(t => t.classList.remove('active'));
                tab.classList.add('active');
                
                // 更新内容显示
                tabContents.forEach(content => {
                    if (content.id === `tab-${tabId}`) {
                        content.classList.remove('hidden');
                        content.classList.add('active');
                    } else {
                        content.classList.add('hidden');
                        content.classList.remove('active');
                    }
                });
            });
        });
    }
    
    /**
     * 设置事件监听器
     */
    setupEventListeners() {
        // 招募村民按钮
        const recruitBtn = document.getElementById('recruit-villager');
        if (recruitBtn) {
            recruitBtn.addEventListener('click', () => {
                const result = gameUtils.recruitVillager(this.gameData);
                if (result.success) {
                    this.showNotification(result.message, 'success');
                    this.updateGameInterface();
                } else {
                    this.showNotification(result.message, 'error');
                }
            });
        }
    }
    
    /**
     * 启动资源更新定时器
     */
    startResourceTimer() {
        setInterval(() => {
            this.updateResources();
        }, 10000); // 每10秒更新一次资源
    }
    
    /**
     * 更新资源
     */
    updateResources() {
        // 获取最新游戏数据
        this.gameData = gameUtils.getGameData();
        
        // 更新资源显示
        this.updateResourcesDisplay();
    }
    
    /**
     * 更新资源显示
     */
    updateResourcesDisplay() {
        const resourcesGrid = document.getElementById('resources-grid');
        if (!resourcesGrid || !this.gameData) return;
        
        // 清空资源网格
        resourcesGrid.innerHTML = '';
        
        // 添加木材资源
        const woodCard = this.createResourceCard(
            'wood', 
            '木材',
            this.gameData.resources.wood,
            'fa-tree',
            '#DEB887'
        );
        resourcesGrid.appendChild(woodCard);
        
        // 添加粮食资源
        const foodCard = this.createResourceCard(
            'food',
            '粮食',
            this.gameData.resources.food,
            'fa-leaf',
            '#8BC34A'
        );
        resourcesGrid.appendChild(foodCard);
        
        // 添加人口资源
        const populationCard = this.createResourceCard(
            'population',
            '人口',
            `${this.gameData.resources.population}/${this.gameData.resources.maxPopulation}`,
            'fa-users',
            '#F08080',
            false
        );
        resourcesGrid.appendChild(populationCard);
    }
    
    /**
     * 创建资源卡片
     * @param {string} id - 资源ID
     * @param {string} name - 资源名称
     * @param {number|string} value - 资源数量
     * @param {string} icon - 图标类名
     * @param {string} color - 颜色
     * @param {boolean} showProduction - 是否显示产出
     * @returns {HTMLElement} 资源卡片元素
     */
    createResourceCard(id, name, value, icon, color, showProduction = true) {
        const card = document.createElement('div');
        card.className = 'resource-card';
        
        // 计算产出
        let productionText = '';
        if (showProduction) {
            const production = this.calculateProduction(id);
            const sign = production >= 0 ? '+' : '';
            productionText = `<div class="text-xs ${production >= 0 ? 'text-success' : 'text-danger'}">
                ${sign}${production.toFixed(1)}/小时
            </div>`;
        }
        
        card.innerHTML = `
            <div class="flex items-center">
                <div class="resource-icon" style="background-color: ${color}20;">
                    <i class="fa ${icon}" style="color: ${color};"></i>
                </div>
                <div>
                    <div class="text-xs text-gray-600">${name}</div>
                    <div class="font-bold" id="${id}-amount">${value}</div>
                </div>
            </div>
            ${productionText}
        `;
        
        return card;
    }
    
    /**
     * 计算资源产出
     * @param {string} resourceId - 资源ID
     * @returns {number} 每小时产出
     */
    calculateProduction(resourceId) {
        if (!this.gameData) return 0;
        
        if (resourceId === 'wood') {
            const sawmill = this.gameData.buildings.find(b => b.id === 'sawmill');
            if (sawmill && sawmill.unlocked) {
                return sawmill.baseProduction * sawmill.level * sawmill.efficiency;
            }
        }
        
        if (resourceId === 'food') {
            const farm = this.gameData.buildings.find(b => b.id === 'farm');
            if (farm && farm.unlocked) {
                const production = farm.baseProduction * farm.level * farm.efficiency;
                const consumption = this.gameData.resources.population * 2;
                return production - consumption;
            }
        }
        
        return 0;
    }
    
    /**
     * 更新游戏界面
     */
    updateGameInterface() {
        this.updateResourcesDisplay();
        // 根据需要添加更多界面更新函数
    }
}

// 导出游戏管理器实例
const gameManager = new GameManager();
export default gameManager;
